package day09.Homework;

import java.io.*;
import java.util.Scanner;

public class Homework3 {
    public static void main(String[] args) {
        String path = "/Users/hao/Desktop/abc3";
        File dir = new File(path);
        if(!dir.isDirectory()){
            System.out.println("不是文件夹");
            return;
        }
        System.out.println("请输入加密密码:");
        int key = new Scanner(System.in).nextInt();
        try {
            getFile(dir, key);
            System.out.println("加密成功");
        } catch (IOException e) {
            System.out.println("加密失败");
            e.printStackTrace();
        }

    }

    private static void getFile(File dir, int key) throws IOException {
        File[] files = dir.listFiles();
        if(files == null){
            return;
        }
        for(File f: files){
            if(f.isFile()){
                //System.out.println(f.getAbsolutePath());
                encrpt(f, key);
            }else{
                getFile(f, key);
            }
        }
    }

    private static void encrpt(File f, int key) throws IOException {
        RandomAccessFile raf = new RandomAccessFile(f.getAbsoluteFile(), "rw");
        byte[] buff = new byte[8192];
        int n = 0;
        while((n = raf.read(buff)) != -1){
            for(int i = 0; i < buff.length; i++){
                buff[i] ^= key;
            }
            raf.seek(raf.getFilePointer() - n);
            raf.write(buff,0, n);
        }
        raf.close();

    }
}
